package com.rzl.expense.quartz.task;


import com.rzl.expense.common.core.domain.entity.SysUser;
import com.rzl.expense.common.utils.DateUtils;
import com.rzl.expense.common.utils.SecurityUtils;
import com.rzl.expense.common.utils.StringUtils;
import com.rzl.expense.agent.DataAgentService;

import com.rzl.expense.system.domain.GroupUser;
import com.rzl.expense.system.service.IGroupUserRoleService;
import com.rzl.expense.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 集团用户同步
 *
 * @author admin
 * @date 2023/08/09
 */
@Slf4j
@Component("GroupUsersTask")  // 2.开启定时任务
public class GroupUsersTask {
    @Autowired
    private DataAgentService dataAgentService;

    @Autowired
    private ISysUserService iSysUserService;

    @Autowired
    private IGroupUserRoleService groupUserRoleService;

    /**
     * 集团用户同步
     */
    public void parseGroupUserData() {
        log.info("获取集团用户数据..........");
        // 执行sql
        List<GroupUser> baseList = (List<GroupUser>) dataAgentService.getData(RuleSqlAdapter.getObtainingGroupUserData(), GroupUser.class);
        log.info("获取集团用户数据：{}条", baseList.size());
        List<GroupUser> baseLists = baseList.stream().filter(r -> StringUtils.isNotEmpty(r.getSmapId())).collect(Collectors.toList());


        // 查询系统中现有所有用户信息并且排除用户编码不为空
        List<SysUser> users = iSysUserService.getUserExcludeUsersCodeAll();

        // 将本地用户集合转化为Map
        Map<String, SysUser> localUserMap = users.stream()
                .filter(u -> u.getGroupSmapId() != null)
                .collect(Collectors.toMap(SysUser::getGroupSmapId, Function.identity()));

        AtomicInteger updateCount = new AtomicInteger();
        AtomicInteger insertCount = new AtomicInteger();

        // 使用Stream遍历远程用户集合，检查是否存在于本地用户集合
        baseLists.forEach(r -> {
            SysUser localUser = localUserMap.get(r.getSmapId());
            if (localUser != null) {
                // 用户id相同，执行更新操作
                localUser.setRegId(r.getRegId());
                localUser.setNickName(r.getUserName());
                localUser.setUserName(r.getUserLoginname());
                localUser.setUserType("00");
                localUser.setEmail(r.getUserEmail());
                localUser.setPhoneNumber(r.getUserPhone());
                // localUser.setPassword(r.getUserPassword());
                localUser.setGroupUserId(r.getUserId());
                localUser.setGroupRegId(r.getRegId());
                localUser.setGroupUserCode(r.getUserCode());
                localUser.setGroupSmapId(r.getSmapId());
                localUser.setGroupPreferredMobile(r.getPreferredMobile());
                localUser.setGroupSmapStatus(r.getSmapStatus());
                localUser.setGroupChangeTime(DateUtils.parseDate(r.getChangeTime()));
                localUser.setGroupSynKind(r.getSynKind());
                localUser.setGroupChangeType(r.getChangeType());
                localUser.setGroupOrgCode(r.getOrgCode());
                localUser.setGroupCityName(r.getCityName());
                localUser.setGroupPrvId(r.getPrvId());
                localUser.setGroupLastModifyTime(DateUtils.parseDate(r.getLastModifyTime()));
                localUser.setGroupIsValid(r.getIsValid());
                localUser.setCreateTime(DateUtils.parseDate(r.getCreateTime()));
                // localUser.setUpdateTime(DateUtils.parseDate(r.getModifyTime()));
                localUser.setUpdateTime(DateUtils.getNowDate());
                localUser.setRemark(r.getUserNote());

                updateCount.getAndIncrement();
                // 修改集团用户相关数据

                List<String> roleIds = groupUserRoleService.selectGroupAuthId(r.getRoleIdStr());
                if (roleIds == null) {
                    roleIds = new ArrayList<>();
                    roleIds.add("3");
                }
                localUser.setRoleIds(roleIds);
                iSysUserService.updateLocalUser(localUser);
            } else {
                // 用户id不存在，执行添加操作
                localUser = new SysUser();
                localUser.setRegId(r.getRegId());
                localUser.setNickName(r.getUserName());
                localUser.setUserName(r.getUserLoginname());
                localUser.setUserType("00");
                localUser.setEmail(r.getUserEmail());
                localUser.setPhoneNumber(r.getUserPhone());
                // 设置默认密码
                localUser.setPassword(SecurityUtils.encryptPassword("iso998f,."));
                localUser.setStatus("1");
                localUser.setDelFlag("0");
                List<String> roleIds = groupUserRoleService.selectGroupAuthId(r.getRoleIdStr());
                if (roleIds == null) {
                    roleIds = new ArrayList<>();
                    roleIds.add("3");
                }
                localUser.setRoleIds(roleIds);
                localUser.setGroupUserId(r.getUserId());
                localUser.setGroupRegId(r.getRegId());
                localUser.setGroupUserCode(r.getUserCode());
                localUser.setGroupSmapId(r.getSmapId());
                localUser.setGroupPreferredMobile(r.getPreferredMobile());
                localUser.setGroupSmapStatus(r.getSmapStatus());
                localUser.setGroupChangeTime(DateUtils.parseDate(r.getChangeTime()));
                localUser.setGroupSynKind(r.getSynKind());
                localUser.setGroupChangeType(r.getChangeType());
                localUser.setGroupOrgCode(r.getOrgCode());
                localUser.setGroupCityName(r.getCityName());
                localUser.setGroupPrvId(r.getPrvId());
                localUser.setGroupLastModifyTime(DateUtils.parseDate(r.getLastModifyTime()));
                localUser.setGroupIsValid(r.getIsValid());
                localUser.setCreateTime(DateUtils.parseDate(r.getCreateTime()));
                // localUser.setUpdateTime(DateUtils.parseDate(r.getModifyTime()));
                localUser.setUpdateTime(DateUtils.getNowDate());
                localUser.setRemark(r.getUserNote());

                insertCount.getAndIncrement();

                // 添加集团用户相关数据
                iSysUserService.insertlocalUser(localUser);
            }
        });
        log.info("数据操作成功");
        log.info("获取集团过滤SMAP账号不为空的数据：{}条", baseLists.size());
        log.info("系统中用户过滤SMAP账号不为空的：{}条", users.size());
        log.info("系统转换成map：{}条", localUserMap.size());
        log.info("新增集团用户：{}条", insertCount.get());
        log.info("修改集团用户：{}条", updateCount.get());
    }
}
